package com.zn.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.crypto.provider.TlsKeyMaterialGenerator;
import com.zn.pojo.User;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    RestHighLevelClient client;

    public static final String TLZ_INDEX = "tlz_index";

    //往es中存数据
    public void addPlayer(User user, String id) throws IOException {
        IndexRequest request = new IndexRequest(TLZ_INDEX).id(id).source(JSON.toJSONString(user), XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
    }

    //往es中获得数据
    public Map<String, Object> getPlayer(String id) throws IOException {
        GetRequest getRequest = new GetRequest(TLZ_INDEX, id);
        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
        return response.getSource();
    }

    //批量插入数据
    public int bluckUser() throws IOException {
        //批量插入的api
        BulkRequest request = new BulkRequest();
        //设置多长时间导入
        request.timeout("10s");
        //定一个集合
        List<User> userList = new ArrayList<>();
        userList.add(new User("tlz", 13));
        userList.add(new User("tlz", 14));
        userList.add(new User("tlz", 15));
        userList.add(new User("tlz", 16));
        userList.add(new User("tlz", 17));
        userList.add(new User("tlz", 18));

        for (int i = 0; i < userList.size(); i++) {
            //将一个一个的单个添加，添加到批量添加
            request.add(new IndexRequest(TLZ_INDEX)
                    .id("" + (i + 1))
                    .source(JSON.toJSONString(userList.get(i)), XContentType.JSON)
            );
        }

        //执行请求
        BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);

        //响应 判断是否成功
        System.out.println(bulk.hasFailures());
        System.out.println(bulk.status());

        return userList.size();
    }

    //更新数据
    public Boolean updateUser(User user, String id) {
        try {
            UpdateRequest ur = new UpdateRequest(TLZ_INDEX, id);
            ur.doc(JSON.toJSONString(user), XContentType.JSON);
            client.update(ur, RequestOptions.DEFAULT);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //删除用户
    public Boolean deleteUser(String id) throws IOException {
        DeleteRequest dr = new DeleteRequest(TLZ_INDEX, id);
        DeleteResponse delete = client.delete(dr, RequestOptions.DEFAULT);
        //删除成功的状态码是200
        int status = delete.status().getStatus();
        if (status == 200) {
            return true;
        }
        return false;
    }

    //单条件匹配查询+分页查询
    public List<User> searchMach(String key, String val) throws IOException {
        //根据索引库查询
        SearchRequest searchRequest = new SearchRequest(TLZ_INDEX);
        //构建查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //精确匹配，那个关键字不会被拆分！
        searchSourceBuilder.query(QueryBuilders.matchQuery(key, val));
        //进行分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(10);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));

        //查询到匹配条件的结果
        SearchHit[] hits = response.getHits().getHits();
        List<User> userList = new LinkedList<>();
        for (SearchHit hit : hits) {
            User player = JSONObject.parseObject(hit.getSourceAsString(), User.class);
            userList.add(player);
        }
        return userList;
    }

    //词条查询
    public List<User> searchTerm(String key, String val) throws IOException {
        //根据索引库查询
        SearchRequest searchRequest = new SearchRequest(TLZ_INDEX);
        //构建查询条件
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        //关键字 会被拆分！
        ssb.query(QueryBuilders.termQuery(key, val));
        //进行分页
        ssb.from(0);
        ssb.size(11);
        searchRequest.source(ssb);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));

        //查询到匹配条件的结果
        SearchHit[] hits = response.getHits().getHits();
        List<User> userList = new ArrayList<>();
        for (SearchHit hit : hits) {
            User player = JSONObject.parseObject(hit.getSourceAsString(), User.class);
            userList.add(player);
        }
        return userList;
    }

    //前缀匹配
    public List<User> searchMatchPrefix(String key, String value) throws IOException {
        SearchRequest searchRequest = new SearchRequest(TLZ_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.prefixQuery(key, value));
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(10);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
        SearchHit[] hits = response.getHits().getHits();
        List<User> playerList = new LinkedList<>();
        for (SearchHit hit : hits) {
            User player = JSONObject.parseObject(hit.getSourceAsString(), User.class);
            playerList.add(player);
        }

        return playerList;
    }

    //多条件查询
    public List<User> searchMore() throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchPhraseQuery("name", "tlz"))
                .must(QueryBuilders.matchPhraseQuery("age", "13"))
        );

        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        List<User> userList = new ArrayList<>();
        for (SearchHit hit : hits) {
            User user = JSONObject.parseObject(hit.getSourceAsString(), User.class);
            userList.add(user);
            System.out.println("===========>" + user);
        }
        return userList;
    }



}

